package com.eb.buybuybuy.init;

import com.eb.buybuybuy.annotation.Entrance;
import com.eb.buybuybuy.annotation.HttpController;
import com.eb.buybuybuy.constant.RequestMethodEnum;
import com.eb.buybuybuy.core.IOC;
import com.eb.buybuybuy.core.router.RequestRouter;
import com.eb.buybuybuy.core.router.bean.RequestRouteEntrance;
import com.eb.buybuybuy.util.PropertiesUtil;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.*;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Properties;

@WebListener
public class Init implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 初始化ioc容器
        IOC.init();

        Map<Class, Object> beanMap = IOC.getBeanMap();
        for (Object object : beanMap.values()) {
            Class clazz = object.getClass();
            HttpController httpController = (HttpController) clazz.getAnnotation(HttpController.class);
            if (httpController == null) {
                // 没有注解，跳过
                continue;
            }
            String rootPath = httpController.value();

            for (Method method : clazz.getDeclaredMethods()) {
                Entrance entrance = method.getAnnotation(Entrance.class);
                if (entrance == null) {
                    // 没有注解，跳过
                    continue;
                }
                String path = entrance.path();
                RequestMethodEnum requestMethod = entrance.method();
                RequestRouteEntrance requestRouteEntrance = new RequestRouteEntrance(clazz, object, method);
                RequestRouter.addRoute(requestMethod, rootPath + path, requestRouteEntrance);
            }
        }
    }
}
